<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>JAVA NIO | 樱桃小窝</title><meta name="keywords" content="NIO"><meta name="author" content="樱桃先生"><meta name="copyright" content="樱桃先生"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="JAVA NIO简介JavaNIO (New IO &#x2F;Non Blocking IO),可以代替标准的Java IO Java NIO 与 IO的主要区别 通道和缓冲区Java NIO系统的核心在于:通道(channel)和缓冲区(Buffer) 通道表示打开到IO设备(文件,套接字)的连接 若需要使用NIO系统,需要获取用于连接IO设备的通道以及用于容纳数据的缓冲区. 然后操作缓冲区,对数据进行">
<meta property="og:type" content="article">
<meta property="og:title" content="JAVA NIO">
<meta property="og:url" content="http://example.com/posts/9da9422b/index.html">
<meta property="og:site_name" content="樱桃小窝">
<meta property="og:description" content="JAVA NIO简介JavaNIO (New IO &#x2F;Non Blocking IO),可以代替标准的Java IO Java NIO 与 IO的主要区别 通道和缓冲区Java NIO系统的核心在于:通道(channel)和缓冲区(Buffer) 通道表示打开到IO设备(文件,套接字)的连接 若需要使用NIO系统,需要获取用于连接IO设备的通道以及用于容纳数据的缓冲区. 然后操作缓冲区,对数据进行">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://ytblogpic.oss-cn-guangzhou.aliyuncs.com/blog-common.png">
<meta property="article:published_time" content="2021-03-11T16:13:00.000Z">
<meta property="article:modified_time" content="2021-03-14T15:56:14.000Z">
<meta property="article:author" content="樱桃先生">
<meta property="article:tag" content="NIO">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://ytblogpic.oss-cn-guangzhou.aliyuncs.com/blog-common.png"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="http://example.com/posts/9da9422b/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'JAVA NIO',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-03-14 23:56:14'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 5.4.2"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="https://s2.loli.net/2022/08/20/hk9Zvq4YRsIcnrw.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">78</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">65</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">21</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间线</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/gallery/"><i class="fa-fw fas fa-camera"></i><span> 图库</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fas fa-comment-dots"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/links/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://ytblogpic.oss-cn-guangzhou.aliyuncs.com/blog-common.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">樱桃小窝</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间线</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/gallery/"><i class="fa-fw fas fa-camera"></i><span> 图库</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fas fa-comment-dots"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/links/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">JAVA NIO</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-03-11T16:13:00.000Z" title="发表于 2021-03-12 00:13:00">2021-03-12</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-03-14T15:56:14.000Z" title="更新于 2021-03-14 23:56:14">2021-03-14</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%8A%80%E6%9C%AF/">技术</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%8A%80%E6%9C%AF/NIO/">NIO</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="JAVA NIO"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="JAVA-NIO"><a href="#JAVA-NIO" class="headerlink" title="JAVA NIO"></a>JAVA NIO</h1><h2 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h2><p>JavaNIO (New IO /Non Blocking IO),可以代替标准的Java IO</p>
<h2 id="Java-NIO-与-IO的主要区别"><a href="#Java-NIO-与-IO的主要区别" class="headerlink" title="Java NIO 与 IO的主要区别"></a>Java NIO 与 IO的主要区别</h2><p><img src= "" data-lazy-src="https://gitee.com/xyingtao/blogimage/raw/master/image-20210313001703545.png" alt="image-20210313001703545"></p>
<h2 id="通道和缓冲区"><a href="#通道和缓冲区" class="headerlink" title="通道和缓冲区"></a>通道和缓冲区</h2><p>Java NIO系统的核心在于:通道(channel)和缓冲区(Buffer) 通道表示打开到IO设备(文件,套接字)的连接</p>
<p>若需要使用NIO系统,需要获取用于连接IO设备的通道以及用于容纳数据的缓冲区. 然后操作缓冲区,对数据进行处理</p>
<p>简而言之 channel负责传输 Buffer 负责存储</p>
<h2 id="Buffer"><a href="#Buffer" class="headerlink" title="Buffer"></a>Buffer</h2><p>除了Boolean 以外,都有对应的类型缓冲区</p>
<p>所有缓冲区的管理方式几乎一致,通过allocate() 获取对应的缓冲区</p>
<h3 id="缓冲区存储数据的两个核心方法"><a href="#缓冲区存储数据的两个核心方法" class="headerlink" title="缓冲区存储数据的两个核心方法"></a>缓冲区存储数据的两个核心方法</h3><p><code>put():</code> 存入数据到缓冲区中</p>
<p><code>get():</code> 获取缓冲区中的数据</p>
<h3 id="缓冲区的四个核心属性"><a href="#缓冲区的四个核心属性" class="headerlink" title="缓冲区的四个核心属性"></a>缓冲区的四个核心属性</h3><p><code>capacity</code>: 容量,表示缓冲区中最大存储数据的容量,一旦声明 不能改变</p>
<p><code>position</code>: 表示缓冲区中正在操作数据的位置 </p>
<p><code>limit</code>: 界限,表示缓冲区中可以操作数据的大小 limit后边的数据不能读写</p>
<p><code>mark</code>: 标记,表示当前position的位置 可以通过reset()恢复到mark的位置</p>
<p>position&lt;=limit&lt;=capacity</p>
<p><img src= "" data-lazy-src="https://gitee.com/xyingtao/blogimage/raw/master/image-20210313003512734.png" alt="~"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">test</span><span class="params">()</span> &#123;</span><br><span class="line">     <span class="type">String</span> <span class="variable">s</span> <span class="operator">=</span> <span class="string">&quot;billy&quot;</span>;</span><br><span class="line">     <span class="type">ByteBuffer</span> <span class="variable">buffer</span> <span class="operator">=</span> ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line">     System.out.println(buffer.position());</span><br><span class="line">     System.out.println(buffer.limit());</span><br><span class="line">     System.out.println(buffer.capacity());</span><br><span class="line">     <span class="comment">//存入数据到缓冲区</span></span><br><span class="line">     buffer.put(s.getBytes());</span><br><span class="line">     System.out.println(buffer.position());</span><br><span class="line">     System.out.println(buffer.limit());</span><br><span class="line">     System.out.println(buffer.capacity());</span><br><span class="line">     <span class="comment">//切换到读取数据</span></span><br><span class="line">     buffer.flip();</span><br><span class="line">     System.out.println(buffer.position());</span><br><span class="line">     System.out.println(buffer.limit());</span><br><span class="line">     System.out.println(buffer.capacity());</span><br><span class="line">     <span class="comment">//rewind 重复读 </span></span><br><span class="line">     <span class="type">byte</span>[] bytes = <span class="keyword">new</span> <span class="title class_">byte</span>[buffer.limit()];</span><br><span class="line">     buffer.get(bytes);</span><br><span class="line">     System.out.println(<span class="keyword">new</span> <span class="title class_">String</span>(bytes,<span class="number">0</span>,bytes.length));</span><br><span class="line"></span><br><span class="line">     buffer.rewind();</span><br><span class="line">     System.out.println(buffer.position());</span><br><span class="line">     System.out.println(buffer.limit());</span><br><span class="line">     System.out.println(buffer.capacity());</span><br><span class="line">     buffer.get(bytes);</span><br><span class="line">     System.out.println(<span class="keyword">new</span> <span class="title class_">String</span>(bytes,<span class="number">0</span>,bytes.length));</span><br><span class="line">     <span class="comment">// clear 清除 </span></span><br><span class="line">     buffer.clear();</span><br><span class="line">     System.out.println(buffer.position());</span><br><span class="line">     System.out.println(buffer.limit());</span><br><span class="line">     System.out.println(buffer.capacity());</span><br><span class="line">     </span><br><span class="line">     buffer.get(bytes);</span><br><span class="line">     System.out.println(<span class="keyword">new</span> <span class="title class_">String</span>(bytes,<span class="number">0</span>,bytes.length));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>







<h3 id="直接缓冲区与非直接缓冲区"><a href="#直接缓冲区与非直接缓冲区" class="headerlink" title="直接缓冲区与非直接缓冲区"></a>直接缓冲区与非直接缓冲区</h3><p><code>非直接缓冲区</code>: 通过allocate()方法分配缓冲区</p>
<p><code>直接缓冲区</code>: 通过allocateDirect() 方法分配缓冲区,就缓冲区建立在物理内存中可以提高效率,在某种情况下</p>
<p><img src= "" data-lazy-src="https://gitee.com/xyingtao/blogimage/raw/master/image-20210313140134613.png" alt="image-20210313140134613"></p>
<p><img src= "" data-lazy-src="https://gitee.com/xyingtao/blogimage/raw/master/image-20210313140549531.png" alt="image-20210313140549531"></p>
<h2 id="通道-Channel"><a href="#通道-Channel" class="headerlink" title="通道(Channel)"></a>通道(Channel)</h2><p><code>通道(Channel)</code>: 由java.nio.channels包定义的. Channel表示IO源与目标打开的链接</p>
<p>Channel类似于传统中的流,只不过Channel本身不能直接访问数据,Channel只能与Buffer进行交互</p>
<p><img src= "" data-lazy-src="https://gitee.com/xyingtao/blogimage/raw/master/image-20210313141537062.png" alt="image-20210313141537062"></p>
<p><img src= "" data-lazy-src="https://gitee.com/xyingtao/blogimage/raw/master/image-20210313142012923.png" alt="image-20210313142012923"></p>
<p>通道是一个完全独立的处理器,拥有一套自己的传输方式</p>
<p>通道的主要实现类</p>
<p>java.nio.channels.channel接口:</p>
<p>FileChannel</p>
<p>SocketChannel</p>
<p>ServerSocketChannel</p>
<p>DataframChannel</p>
<h3 id="获取通道"><a href="#获取通道" class="headerlink" title="获取通道:"></a>获取通道:</h3><ol>
<li><p>Java针对支持通道的类提供类getChannel()方法</p>
<p>本地IO:</p>
<p>FileInputStream/FileOutputStream</p>
<p>RandomAccessFile</p>
<p>网络IO:</p>
<p>Socket</p>
<p>ServerSocket</p>
<p>DatagramSocket</p>
</li>
<li><p>在JDK1.7中的NIO2针对各个通道提供类静态方法open()</p>
</li>
<li><p>在JDK1.7中的NIO2的Files工具类的newByteChannel()</p>
</li>
</ol>
<h3 id="使用通道完成文件复制"><a href="#使用通道完成文件复制" class="headerlink" title="使用通道完成文件复制"></a>使用通道完成文件复制</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">test1</span><span class="params">()</span> &#123;</span><br><span class="line">    FileInputStream fis= <span class="literal">null</span>;</span><br><span class="line">    <span class="type">FileOutputStream</span> <span class="variable">fos</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">    <span class="type">FileChannel</span> <span class="variable">inc</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">    <span class="type">FileChannel</span> <span class="variable">ouc</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        fis = <span class="keyword">new</span> <span class="title class_">FileInputStream</span>(<span class="string">&quot;src/main/resources/1.jpg&quot;</span>);</span><br><span class="line">        fos = <span class="keyword">new</span> <span class="title class_">FileOutputStream</span>(<span class="string">&quot;src/main/resources/2.jpg&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//获取通道</span></span><br><span class="line">        inc = fis.getChannel();</span><br><span class="line">        ouc = fos.getChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//分配指定的缓冲区大小</span></span><br><span class="line">        <span class="type">ByteBuffer</span> <span class="variable">buf</span> <span class="operator">=</span> ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//开始读取数据</span></span><br><span class="line">        <span class="keyword">while</span>(inc.read(buf)!=-<span class="number">1</span>)&#123;</span><br><span class="line">            buf.flip();<span class="comment">//切换成读取数据的模式</span></span><br><span class="line">            ouc.write(buf);</span><br><span class="line">            buf.clear();<span class="comment">//清空缓冲区</span></span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">        e.printStackTrace();</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (ouc!=<span class="literal">null</span>)&#123;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                ouc.close();</span><br><span class="line">            &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (inc!=<span class="literal">null</span>)&#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                inc.close();</span><br><span class="line">            &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (fos!=<span class="literal">null</span>)&#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                fos.close();</span><br><span class="line">            &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (fis!=<span class="literal">null</span>)&#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                fis.close();</span><br><span class="line">            &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<h2 id="使用直接缓冲区完成文件的复制"><a href="#使用直接缓冲区完成文件的复制" class="headerlink" title="使用直接缓冲区完成文件的复制"></a>使用直接缓冲区完成文件的复制</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">test2</span><span class="params">()</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">    <span class="type">FileChannel</span> <span class="variable">inc</span> <span class="operator">=</span> FileChannel.open(Paths.get(<span class="string">&quot;src/main/resources/1.jpg&quot;</span>), StandardOpenOption.READ);</span><br><span class="line">    <span class="type">FileChannel</span> <span class="variable">ouc</span> <span class="operator">=</span> FileChannel.open(Paths.get(<span class="string">&quot;src/main/resources/3.jpg&quot;</span>), StandardOpenOption.WRITE,StandardOpenOption.READ);</span><br><span class="line">    <span class="comment">//内存映射文件</span></span><br><span class="line">    <span class="type">MappedByteBuffer</span> <span class="variable">inMapBuf</span> <span class="operator">=</span> inc.map(FileChannel.MapMode.READ_ONLY, <span class="number">0</span>, inc.size());</span><br><span class="line">    <span class="type">MappedByteBuffer</span> <span class="variable">ouMapBuf</span> <span class="operator">=</span> ouc.map(FileChannel.MapMode.READ_WRITE, <span class="number">0</span>, inc.size());</span><br><span class="line"></span><br><span class="line">    <span class="comment">//这种方式不用通过通道 直接在内存中操作 直接对缓冲区进行数据的读写操作</span></span><br><span class="line">    <span class="type">byte</span>[] dst = <span class="keyword">new</span> <span class="title class_">byte</span>[inMapBuf.limit()];</span><br><span class="line">    inMapBuf.get(dst);</span><br><span class="line">    ouMapBuf.put(dst);</span><br><span class="line">    inc.close();</span><br><span class="line">    ouc.close();</span><br><span class="line">    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="通道之间的数据传输"><a href="#通道之间的数据传输" class="headerlink" title="通道之间的数据传输"></a>通道之间的数据传输</h2><p>transferFrom()</p>
<p>transferTo()</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">test3</span><span class="params">()</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">    <span class="type">FileChannel</span> <span class="variable">inc</span> <span class="operator">=</span> FileChannel.open(Paths.get(<span class="string">&quot;src/main/resources/1.jpg&quot;</span>), StandardOpenOption.READ);</span><br><span class="line">    <span class="type">FileChannel</span> <span class="variable">ouc</span> <span class="operator">=</span> FileChannel.open(Paths.get(<span class="string">&quot;src/main/resources/4.jpg&quot;</span>), StandardOpenOption.WRITE,StandardOpenOption.READ);</span><br><span class="line">    inc.transferTo(<span class="number">0</span>,inc.size(),ouc);</span><br><span class="line"></span><br><span class="line">    inc.close();</span><br><span class="line">    ouc.close();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="分散与聚集"><a href="#分散与聚集" class="headerlink" title="分散与聚集"></a>分散与聚集</h2><p>分散读取(Scatter Reads) 将通道中的数据分散到多个缓冲区中去</p>
<p>聚集写入(Gathering Writes) 将多个缓冲区中的数据</p>
<p><img src= "" data-lazy-src="https://gitee.com/xyingtao/blogimage/raw/master/image-20210313154304838.png" alt="image-20210313154304838"></p>
<p><img src= "" data-lazy-src="https://gitee.com/xyingtao/blogimage/raw/master/image-20210313154339490.png" alt="image-20210313154339490"></p>
<h2 id="字符集-Charset"><a href="#字符集-Charset" class="headerlink" title="字符集: Charset"></a>字符集: Charset</h2><p>编码: 字符串 -&gt; 字节数组</p>
<p>解码: 字节数组 -&gt; 字符串</p>
<h2 id="阻塞与非阻塞"><a href="#阻塞与非阻塞" class="headerlink" title="阻塞与非阻塞"></a>阻塞与非阻塞</h2><p>通过NIO完成网络通信的三个核心</p>
<ol>
<li><p>通道: 负责连接</p>
<p>SelectableChannel</p>
<pre><code>- SocketChannel
- ServerSocketChannel
- DatagramChannel
- Pipe.SinkChannel
- Pipe.SourceChannel
</code></pre>
</li>
<li><p>缓冲区: 负责数据的存取</p>
</li>
<li><p>选择器: 是SelectableChannel的多路复用器.用于监控SelectableChannel的IO状态</p>
</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TestBlockingNIO</span> &#123;</span><br><span class="line">    <span class="comment">//客户端</span></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">client</span><span class="params">()</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">        <span class="comment">//1.获取通道</span></span><br><span class="line">        <span class="type">SocketChannel</span> <span class="variable">sChannel</span> <span class="operator">=</span> SocketChannel.open(<span class="keyword">new</span> <span class="title class_">InetSocketAddress</span>(<span class="string">&quot;127.0.0.1&quot;</span>, <span class="number">9898</span>));</span><br><span class="line">        <span class="type">FileChannel</span> <span class="variable">inChannel</span> <span class="operator">=</span> FileChannel.open(Paths.get(<span class="string">&quot;src/main/resources/1.jpg&quot;</span>), StandardOpenOption.READ);</span><br><span class="line">        <span class="comment">//2.分配指定大小的Buffer</span></span><br><span class="line">        <span class="type">ByteBuffer</span> <span class="variable">buf</span> <span class="operator">=</span> ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line">        <span class="comment">//3.读取本地文件发送到服务端</span></span><br><span class="line">        <span class="keyword">while</span>(inChannel.read(buf)!=-<span class="number">1</span>)&#123;</span><br><span class="line">            buf.flip();</span><br><span class="line">            sChannel.write(buf);</span><br><span class="line">            buf.clear();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//4.关闭通道</span></span><br><span class="line">        inChannel.close();</span><br><span class="line">        sChannel.close();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//服务端</span></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">server</span><span class="params">()</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">        <span class="comment">//1.获取通道</span></span><br><span class="line">        <span class="type">ServerSocketChannel</span> <span class="variable">ssChannel</span> <span class="operator">=</span> ServerSocketChannel.open();</span><br><span class="line">        <span class="type">FileChannel</span> <span class="variable">outChannel</span> <span class="operator">=</span> FileChannel.open(Paths.get(<span class="string">&quot;2.jpg&quot;</span>), StandardOpenOption.WRITE, StandardOpenOption.CREATE);</span><br><span class="line">        <span class="comment">//2.绑定连接</span></span><br><span class="line">        ssChannel.bind(<span class="keyword">new</span> <span class="title class_">InetSocketAddress</span>(<span class="number">9898</span>));</span><br><span class="line"></span><br><span class="line">        <span class="comment">//3.获取客户端连接的通道</span></span><br><span class="line">        <span class="type">SocketChannel</span> <span class="variable">sChannel</span> <span class="operator">=</span> ssChannel.accept();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//4.分配指定大小的缓冲区</span></span><br><span class="line">        <span class="type">ByteBuffer</span> <span class="variable">buf</span> <span class="operator">=</span> ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//5.读取客户端的数据并保存到本地</span></span><br><span class="line">        <span class="keyword">while</span>(sChannel.read(buf)!=-<span class="number">1</span>)&#123;</span><br><span class="line">            buf.flip();</span><br><span class="line">            outChannel.write(buf);</span><br><span class="line">            buf.clear();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//6.关闭通道</span></span><br><span class="line">        sChannel.close();</span><br><span class="line">        outChannel.close();</span><br><span class="line">        ssChannel.close();</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

</article><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/NIO/">NIO</a></div><div class="post_share"><div class="social-share" data-image="https://ytblogpic.oss-cn-guangzhou.aliyuncs.com/blog-common.png" data-sites="wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://s2.loli.net/2022/08/21/Ay5sujrkH1nLTwW.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://s2.loli.net/2022/08/21/Ay5sujrkH1nLTwW.jpg" alt="Wechat"/></a><div class="post-qr-code-desc">Wechat</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/posts/9d491d1a/"><img class="prev-cover" src= "" data-lazy-src="https://ytblogpic.oss-cn-guangzhou.aliyuncs.com/blog-common.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Java并发编程的艺术</div></div></a></div><div class="next-post pull-right"><a href="/posts/7dadd78d/"><img class="next-cover" src= "" data-lazy-src="https://ytblogpic.oss-cn-guangzhou.aliyuncs.com/blog-common.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">VUE基础</div></div></a></div></nav><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="https://s2.loli.net/2022/08/20/hk9Zvq4YRsIcnrw.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">樱桃先生</div><div class="author-info__description">樱桃先生的博客小站</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">78</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">65</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">21</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://ytblogpic.oss-cn-guangzhou.aliyuncs.com/typoraWechat.jpeg"><i class="fab fa-weixin"></i><span>加为好友</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">欢迎光临樱桃小窝🍒～评论系统日常崩溃，没有找到长期稳定好用的组件。</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#JAVA-NIO"><span class="toc-number">1.</span> <span class="toc-text">JAVA NIO</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AE%80%E4%BB%8B"><span class="toc-number">1.1.</span> <span class="toc-text">简介</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Java-NIO-%E4%B8%8E-IO%E7%9A%84%E4%B8%BB%E8%A6%81%E5%8C%BA%E5%88%AB"><span class="toc-number">1.2.</span> <span class="toc-text">Java NIO 与 IO的主要区别</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%80%9A%E9%81%93%E5%92%8C%E7%BC%93%E5%86%B2%E5%8C%BA"><span class="toc-number">1.3.</span> <span class="toc-text">通道和缓冲区</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Buffer"><span class="toc-number">1.4.</span> <span class="toc-text">Buffer</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BC%93%E5%86%B2%E5%8C%BA%E5%AD%98%E5%82%A8%E6%95%B0%E6%8D%AE%E7%9A%84%E4%B8%A4%E4%B8%AA%E6%A0%B8%E5%BF%83%E6%96%B9%E6%B3%95"><span class="toc-number">1.4.1.</span> <span class="toc-text">缓冲区存储数据的两个核心方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BC%93%E5%86%B2%E5%8C%BA%E7%9A%84%E5%9B%9B%E4%B8%AA%E6%A0%B8%E5%BF%83%E5%B1%9E%E6%80%A7"><span class="toc-number">1.4.2.</span> <span class="toc-text">缓冲区的四个核心属性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%9B%B4%E6%8E%A5%E7%BC%93%E5%86%B2%E5%8C%BA%E4%B8%8E%E9%9D%9E%E7%9B%B4%E6%8E%A5%E7%BC%93%E5%86%B2%E5%8C%BA"><span class="toc-number">1.4.3.</span> <span class="toc-text">直接缓冲区与非直接缓冲区</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%80%9A%E9%81%93-Channel"><span class="toc-number">1.5.</span> <span class="toc-text">通道(Channel)</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%8E%B7%E5%8F%96%E9%80%9A%E9%81%93"><span class="toc-number">1.5.1.</span> <span class="toc-text">获取通道:</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E9%80%9A%E9%81%93%E5%AE%8C%E6%88%90%E6%96%87%E4%BB%B6%E5%A4%8D%E5%88%B6"><span class="toc-number">1.5.2.</span> <span class="toc-text">使用通道完成文件复制</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E7%9B%B4%E6%8E%A5%E7%BC%93%E5%86%B2%E5%8C%BA%E5%AE%8C%E6%88%90%E6%96%87%E4%BB%B6%E7%9A%84%E5%A4%8D%E5%88%B6"><span class="toc-number">1.6.</span> <span class="toc-text">使用直接缓冲区完成文件的复制</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%80%9A%E9%81%93%E4%B9%8B%E9%97%B4%E7%9A%84%E6%95%B0%E6%8D%AE%E4%BC%A0%E8%BE%93"><span class="toc-number">1.7.</span> <span class="toc-text">通道之间的数据传输</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%86%E6%95%A3%E4%B8%8E%E8%81%9A%E9%9B%86"><span class="toc-number">1.8.</span> <span class="toc-text">分散与聚集</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AD%97%E7%AC%A6%E9%9B%86-Charset"><span class="toc-number">1.9.</span> <span class="toc-text">字符集: Charset</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%98%BB%E5%A1%9E%E4%B8%8E%E9%9D%9E%E9%98%BB%E5%A1%9E"><span class="toc-number">1.10.</span> <span class="toc-text">阻塞与非阻塞</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/posts/4995/" title="顺德好友小聚"><img src= "" data-lazy-src="https://ytblogpic.oss-cn-guangzhou.aliyuncs.com/blog-common.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="顺德好友小聚"/></a><div class="content"><a class="title" href="/posts/4995/" title="顺德好友小聚">顺德好友小聚</a><time datetime="2023-05-07T13:41:30.660Z" title="更新于 2023-05-07 21:41:30">2023-05-07</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/posts/51438/" title="旅游归来的周末"><img src= "" data-lazy-src="https://ytblogpic.oss-cn-guangzhou.aliyuncs.com/blog-common.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="旅游归来的周末"/></a><div class="content"><a class="title" href="/posts/51438/" title="旅游归来的周末">旅游归来的周末</a><time datetime="2023-05-06T06:06:54.933Z" title="更新于 2023-05-06 14:06:54">2023-05-06</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/posts/34851/" title="与好友的广西之旅"><img src= "" data-lazy-src="https://ytblogpic.oss-cn-guangzhou.aliyuncs.com/blog-common.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="与好友的广西之旅"/></a><div class="content"><a class="title" href="/posts/34851/" title="与好友的广西之旅">与好友的广西之旅</a><time datetime="2023-05-02T08:08:36.497Z" title="更新于 2023-05-02 16:08:36">2023-05-02</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/posts/36794/" title="信用卡业务汇总"><img src= "" data-lazy-src="https://s2.loli.net/2022/08/22/kpfRHFaCWDTNAu1.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="信用卡业务汇总"/></a><div class="content"><a class="title" href="/posts/36794/" title="信用卡业务汇总">信用卡业务汇总</a><time datetime="2023-05-02T06:30:21.691Z" title="更新于 2023-05-02 14:30:21">2023-05-02</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/posts/53652/" title="项目管理笔记"><img src= "" data-lazy-src="https://ytblogpic.oss-cn-guangzhou.aliyuncs.com/blog-common.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="项目管理笔记"/></a><div class="content"><a class="title" href="/posts/53652/" title="项目管理笔记">项目管理笔记</a><time datetime="2023-05-02T06:29:26.948Z" title="更新于 2023-05-02 14:29:26">2023-05-02</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://ytblogpic.oss-cn-guangzhou.aliyuncs.com/blog-common.png')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By 樱桃先生</div><div class="footer_custom_text">一切都是最好的安排</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><div class="js-pjax"><script>(()=>{
  const init = () => {
    twikoo.init(Object.assign({
      el: '#twikoo-wrap',
      envId: 'https://twikoo-seven-fawn.vercel.app',
      region: '',
      onCommentLoaded: function () {
        btf.loadLightbox(document.querySelectorAll('#twikoo .tk-content img:not(.tk-owo-emotion)'))
      }
    }, null))
  }

  const getCount = () => {
    const countELement = document.getElementById('twikoo-count')
    if(!countELement) return
    twikoo.getCommentsCount({
      envId: 'https://twikoo-seven-fawn.vercel.app',
      region: '',
      urls: [window.location.pathname],
      includeReply: false
    }).then(function (res) {
      countELement.innerText = res[0].count
    }).catch(function (err) {
      console.error(err);
    });
  }

  const runFn = () => {
    init()
    
  }

  const loadTwikoo = () => {
    if (typeof twikoo === 'object') {
      setTimeout(runFn,0)
      return
    } 
    getScript('https://cdn.jsdelivr.net/npm/twikoo/dist/twikoo.all.min.js').then(runFn)
  }

  if ('Twikoo' === 'Twikoo' || !true) {
    if (true) btf.loadComment(document.getElementById('twikoo-wrap'), loadTwikoo)
    else loadTwikoo()
  } else {
    window.loadOtherComment = () => {
      loadTwikoo()
    }
  }
})()</script></div><script>window.addEventListener('load', () => {
  const changeContent = (content) => {
    if (content === '') return content

    content = content.replace(/<img.*?src="(.*?)"?[^\>]+>/ig, '[图片]') // replace image link
    content = content.replace(/<a[^>]+?href=["']?([^"']+)["']?[^>]*>([^<]+)<\/a>/gi, '[链接]') // replace url
    content = content.replace(/<pre><code>.*?<\/pre>/gi, '[代码]') // replace code
    content = content.replace(/<[^>]+>/g,"") // remove html tag

    if (content.length > 150) {
      content = content.substring(0,150) + '...'
    }
    return content
  }

  const getComment = () => {
    const runTwikoo = () => {
      twikoo.getRecentComments({
        envId: 'https://twikoo-seven-fawn.vercel.app',
        region: '',
        pageSize: 6,
        includeReply: true
      }).then(function (res) {
        const twikooArray = res.map(e => {
          return {
            'content': changeContent(e.comment),
            'avatar': e.avatar,
            'nick': e.nick,
            'url': e.url + '#' + e.id,
            'date': new Date(e.created).toISOString()
          }
        })

        saveToLocal.set('twikoo-newest-comments', JSON.stringify(twikooArray), 10/(60*24))
        generateHtml(twikooArray)
      }).catch(function (err) {
        const $dom = document.querySelector('#card-newest-comments .aside-list')
        $dom.innerHTML= "无法获取评论，请确认相关配置是否正确"
      })
    }

    if (typeof twikoo === 'object') {
      runTwikoo()
    } else {
      getScript('https://cdn.jsdelivr.net/npm/twikoo/dist/twikoo.all.min.js').then(runTwikoo)
    }
  }

  const generateHtml = array => {
    let result = ''

    if (array.length) {
      for (let i = 0; i < array.length; i++) {
        result += '<div class=\'aside-list-item\'>'

        if (true) {
          const name = 'data-lazy-src'
          result += `<a href='${array[i].url}' class='thumbnail'><img ${name}='${array[i].avatar}' alt='${array[i].nick}'></a>`
        }
        
        result += `<div class='content'>
        <a class='comment' href='${array[i].url}' title='${array[i].content}'>${array[i].content}</a>
        <div class='name'><span>${array[i].nick} / </span><time datetime="${array[i].date}">${btf.diffDate(array[i].date, true)}</time></div>
        </div></div>`
      }
    } else {
      result += '没有评论'
    }

    let $dom = document.querySelector('#card-newest-comments .aside-list')
    $dom.innerHTML= result
    window.lazyLoadInstance && window.lazyLoadInstance.update()
    window.pjax && window.pjax.refresh($dom)
  }

  const newestCommentInit = () => {
    if (document.querySelector('#card-newest-comments .aside-list')) {
      const data = saveToLocal.get('twikoo-newest-comments')
      if (data) {
        generateHtml(JSON.parse(data))
      } else {
        getComment()
      }
    }
  }

  newestCommentInit()
  document.addEventListener('pjax:complete', newestCommentInit)
})</script><script src="/js/jquery.min.js"></script><div class="aplayer no-destroy" data-id="5225697049" data-server="netease" data-type="playlist" data-fixed="true" data-autoplay="false" data-mini="true" data-lrctype="-1"> </div><script src="https://cdn.jsdelivr.net/gh/xiabo2/CDN@latest/fishes.js"></script><link rel="stylesheet" href="/css/utils.css"><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="true"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/metingjs/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = ["head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.tocScrollFn && window.removeEventListener('scroll', window.tocScrollFn)
  window.scrollCollect && window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  document.getElementById('rightside').style.cssText = "opacity: ''; transform: ''"
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

  typeof disqusjs === 'object' && disqusjs.destroy()
})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"model":{"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"right","width":170,"height":280},"mobile":{"show":true},"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body></html>